package com.yxh.controller;

import com.github.pagehelper.PageInfo;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.yxh.common.annotation.Authorization;
import com.yxh.pojo.*;
import com.yxh.service.ChangeService;
import com.yxh.service.FlowManageService;
import com.yxh.service.ViciousService;
import com.yxh.util.*;

import net.sf.json.JSONObject;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yxh.util.APIErrorCode.SUCCESS;

/**
 * Created by asus on 2018/6/26.
 *
 * 设计变更流程管理
 */

@Scope("prototype")
@RestController
@RequestMapping(value = "/change")
public class ChangeController extends BaseController{


    private static final Logger logger = LoggerFactory.getLogger(ChangeController.class);
    private Response response;

    @Autowired
    private ChangeService changeService;


    @Autowired
    private FlowManageService flowManageService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ViciousService viciousService;

    /**
     *新增 启动变更流程
     *
     * @param change
     * @return
     */
    @PostMapping
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response saveChange(@RequestBody Change change) {
        String id=SnowflakeIdWorker.creatId();
        change.setChangeId(id);
        response = Response.returnResponse(APIErrorCode.SUCCESS);
        response.setData(changeService.save(change));

        //启动流程  保存记录
       Map<String,Object> variables = new HashMap<String, Object>();
        variables.put("changeId",id);
        variables.put("code",change.getChangeCode());
        variables.put("user",change.getAuditingId());//指定人


        flowManageService.start(variables,TaskCode.CHANGE_KEY.getDesc(), TaskCode.OPERATION_MEG1.getDesc(),TaskCode.OPERATION_COMMENT1.getDesc());

        History h=new History(); //存历史记录
        h.setUserid(change.getUserId());
        h.setViciousId(id);
       // h.setComment("");
        h.setOperationName(TaskCode.OPERATION_COMMENT15.getDesc());
         viciousService.insertHistroy(h);
        return response;
    }

    @GetMapping("/task/{id}")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response list(@RequestParam(required = false, defaultValue = "1", name = "page") String page,
                         @RequestParam(required = false, defaultValue = "10", name = "pageSize") String pageSize,
                         @PathVariable(value = "id") String id) throws Exception {

        try {

            //查询当前流程的任务
            List<Task> taskList= flowManageService.taskList(page,pageSize,id,TaskCode.CHANGE_KEY.getDesc());

            List<MyTask> tasks = new ArrayList<MyTask>();

            for (Task task : taskList) {
                String changeId= (String) taskService.getVariable(task.getId(), "changeId");
                MyTask t = new MyTask();
                t.setId(task.getId());
                t.setName(task.getName());
                t.setCreateTime(task.getCreateTime());
                Map<String,Object> m=changeService.getById(changeId);
                t.setModel(m==null?new JSONObject():m);
                tasks.add(t);
            }
            //对数据进行转换
            JSONObject result=flowManageService.changeData(tasks,TaskCode.CHANGE_KEY.getDesc(),id);

            response= Response.returnResponse(APIErrorCode.SUCCESS);
            response.setData(result);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.returnResponse(APIErrorCode.SELECT_ERROR);
        }

        return response;
    }


    @GetMapping("/{id}")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response list(@PathVariable(value = "id") String id) throws Exception {

        try {
            response= Response.returnResponse(APIErrorCode.SUCCESS);
            response.setData(changeService.getNewById(id));
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.returnResponse(APIErrorCode.SELECT_ERROR);
        }

        return response;
    }


    @PostMapping("/audit")
    // @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response audit(@RequestBody TaskParam param){

        Map<String, Object> variables = new HashMap<String, Object>();
        String taskId=param.getTaskId(),nextId=param.getNextId(),cs,imgs=param.getUrl(),
        changeId= (String) taskService.getVariable(taskId, "changeId"),megs="",operation="";
        int state,i=0;
        try{
            state=param.getState();
       }catch(Exception e){
           state=0;
       }
        cs=TaskCode.STATE_MEG4.getDesc();
        if(state!=0){
            variables.put("meg",state);

            if(state==TaskCode.STATE_1.getValue()){
                //存在受阻
                variables.put("user1",nextId);
                operation=TaskCode.OPERATION_MEG2.getDesc();
                megs=TaskCode.OPERATION_COMMENT2.getDesc();
               cs=TaskCode.STATE_MEG14.getDesc();
            }

            if(state==TaskCode.STATE_2.getValue()){
                //设计变更审核
                variables.put("user2",nextId);
                operation=TaskCode.OPERATION_MEG3.getDesc();
                megs=TaskCode.OPERATION_COMMENT3.getDesc();
                cs=TaskCode.STATE_MEG15.getDesc();
            }
            if(state==TaskCode.STATE_3.getValue()){
                //不存在受阻
                operation=TaskCode.OPERATION_MEG2.getDesc();
                megs=TaskCode.OPERATION_COMMENT4.getDesc();

            }
            if(state==TaskCode.STATE_4.getValue()){
                //不变更
                operation=TaskCode.OPERATION_MEG3.getDesc();
                megs=TaskCode.OPERATION_COMMENT6.getDesc();

            }
        }

        else{
            operation=TaskCode.OPERATION_MEG4.getDesc();
            megs=TaskCode.OPERATION_COMMENT5.getDesc();

        }
        //提交流程
        flowManageService.complete(taskId,variables,operation,megs);

        //保存历史记录

        History h=new History();
        h.setOperationName(operation);
        h.setState(megs);
        h.setViciousId(changeId);
        h.setComment(param.getComment());
        h.setUserid(param.getUserId());
        if(StringUtil.isNotEmpty(imgs)){
            String id= SnowflakeIdWorker.creatId();
            flowManageService.insertImgs(imgs,id);
            h.setImgId(id);
        }
        h.setPresideId(nextId);

        i=viciousService.insertHistroy(h);

         //更改变更清单状态
        Change c=new  Change();
        c.setChangeId(changeId);
        c.setState(cs);
        i=changeService.update(c);

        response= Response.returnResponse(APIErrorCode.SUCCESS);
        response.setData(i);
        return response;
    }


    @GetMapping
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response getInformation(Change change, String page, String pageSize) {
        Integer limit;
        Integer offset;
        try {
            limit = Integer.parseInt(page);
            offset = Integer.parseInt(pageSize);
        } catch (Exception e) {
            limit = 1;
            offset = 10;
        }
      //  vicious.setDay(DateUtils.parseDate(vicious.getDate()));
        PageInfo pageInfo = changeService.getInformation(change, limit, offset);
        response = Response.returnResponse(SUCCESS);
        response.setData(pageInfo);
        return response;
    }


}
